package com.xingfly.mq;

import com.xingfly.constant.MQConstant;
import com.xingfly.model.Event;
import com.xingfly.model.Image;
import com.xingfly.model.dto.EventImageDTO;
import com.xingfly.model.vo.ImageVO;
import com.xingfly.service.EventService;
import com.xingfly.service.ImageService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by SuperS on 24/05/2017.
 *
 * @author SuperS
 */
@Component
@RabbitListener(queues = MQConstant.EVENT_IMAGE_MQ)
public class EventImageRelationReceiver {
    @Autowired
    private ImageService imageService;
    @Autowired
    private EventService eventService;

    @RabbitHandler
    public void process(EventImageDTO eventImageDTO) {
        //根据EventID查找事件对象
        Event event = eventService.findByEventId(eventImageDTO.getEventId());
        if (event != null)
            for (ImageVO imageVO : eventImageDTO.getImageVOS()) {
            //根据图片id查找图片对象
                Image image = imageService.findById(imageVO.getId());
                if (image != null) {
                    //获取图片已经关联的事件
                    List<Event> eventList = image.getEvents();
                    //将新事件添加到世界列表
                    eventList.add(event);
                    //保存图片和事件的关系
                    image.setEvents(eventList);
                    //更新图片
                    imageService.save(image);
                }
            }
    }
}
